/**
 * @author luguoxiang
 * @date 2021-09-07
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
import { distinct, mergeLoad, request } from '@/soar';

const baseUri = '/system/public';

export const captchaUrl = `${baseUri}/captcha`;

/**
 * 获取rsa动态公钥
 * @param bizType
 */
export function rsaDynamicPKI(bizType: string): Promise<any> {
  return request.get(`${baseUri}/rsaDynamicPKI`, { title: '获取rsa动态公钥', params: { bizType } });
}

/**
 * 获取sm2动态公钥
 * @param bizType
 */
export function sm2DynamicPKI(bizType: string): Promise<any> {
  return request.get(`${baseUri}/sm2DynamicPKI`, { title: '获取sm2动态公钥', params: { bizType } });
}

/**
 * 获取枚举
 * @param names
 */
export function enums(...names: string[]): Promise<any> {
  return request.get(`${baseUri}/enums`, { title: '获取枚举信息', data: { names } });
}

/**
 * 获取验证码
 */
export function captcha(bizType): Promise<any> {
  return request.get(captchaUrl, { title: '获取图片验证码', params: { toBase64: true, bizType } });
}

/**
 * 生成二维码
 * @param params
 */
export function genQrcode(params: object): Promise<any> {
  return request.get(`${baseUri}/genQrcode`, { title: '生成二维码', data: { ...params, toBase64: true } });
}

/**
 * 二维码解码
 */
export function decodeQrcode(file: File): Promise<any> {
  return request.upload(`${baseUri}/decodeQrcode`, { title: '生成二维码', files: file, name: 'file' });
}

/**
 * 获取数据字典
 * @param codes 字典code，支持多个
 */
export function getDicts(codes: string | string[]) {
  if (typeof codes === 'string') {
    codes = codes.split(',');
  }
  return mergeLoad({
    params: codes,
    name: 'dict',
    loader: (codes: string[][]) => {
      const params = distinct(codes.flatMap((x) => x));
      return request.get('/system/dict-item/map', { params: { codes: params.join(',') } });
    },
    responseHandler: (res, params) => {
      const data: any = {};
      for (const code of params) {
        data[code] = res.data[code];
      }
      return {
        ...res,
        data,
      };
    },
  });
}
